package exercise;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;

/*
 * 锟斤拷业4锟斤拷
锟斤拷锟斤拷锟斤拷锟缴碉拷锟侥硷拷锟叫ｏ拷锟斤拷锟斤拷10锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷10锟斤拷女锟斤拷锟斤拷锟斤拷锟斤拷.
锟斤拷锟姐到锟斤拷学锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷锟劫憋拷锟姐到锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷耍锟斤拷趴锟绞硷拷诙锟斤拷值锟斤拷锟�
 */
public class Exercise10 {
	public static void main(String[] args) throws Exception {
		
	/*  BufferedReader br = new BufferedReader(new FileReader("names.txt"));
	  String line;
	  int count =0;
	  BufferedWriter bw = new BufferedWriter(new FileWriter("names1.txt"));
		while((line=br.readLine())!=null){
	      bw.write(line);
	      bw.newLine();
	      count++;
	      if(count==10){
	    	  break;
	      }
	    }
	  bw.close();
	  br.close();
*/
      String src = "names1.txt";
      String backups = "backups.txt";
      ArrayList<String> list = readFile(src);
      if (list.size() == 0) {
          list = readFile(backups);
          writeFile(src, list, false);
          new File(backups).delete();
      }

      Collections.shuffle(list);
      String stuInfo = list.remove(0);
      System.out.println("当前被点到的学生为：" + stuInfo);
      writeFile(src, list, false);
      writeFile(backups, stuInfo, true);


  }

  private static void writeFile(String pathFile, ArrayList<String> list, boolean isAppend) throws IOException {
      BufferedWriter bw = new BufferedWriter(new FileWriter(pathFile, isAppend));
      for (String str : list) {
          bw.write(str);
          bw.newLine();
      }
      bw.close();
  }

  private static void writeFile(String pathFile, String str, boolean isAppend) throws IOException {
      BufferedWriter bw = new BufferedWriter(new FileWriter(pathFile, isAppend));
      bw.write(str);
      bw.newLine();
      bw.close();
  }


  private static ArrayList<String> readFile(String pathFile) throws IOException {
      ArrayList<String> list = new ArrayList<>();
      BufferedReader br = new BufferedReader(new FileReader(pathFile));
      String line;
      while ((line = br.readLine()) != null) {
          list.add(line);
      }
      br.close();
      return list;
  }

}
